package org.example.servicecounselor.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.manage.bean.po.Counselor;
import org.example.model.manage.bean.po.Faculty;
import org.example.model.manage.bean.po.security.User;
import org.example.servicecounselor.mapper.CounselorMapper;
import org.example.servicecounselor.mapper.FacultyMapper;
import org.example.servicecounselor.mapper.UserMapper;
import org.example.servicecounselor.mapper.UserRoleMapper;
import org.example.model.manage.bean.po.security.UserRole;
import org.example.servicecounselor.service.CounselorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  辅导员服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-16
 */
@Service
public class CounselorServiceImpl extends ServiceImpl<CounselorMapper, Counselor> implements CounselorService {

    @Autowired
    private CounselorMapper counselorMapper;

    @Autowired
    private FacultyMapper facultyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Counselor getCounselorById(Integer id) {
        return counselorMapper.selectById(id);
    }

    @Override
    public Counselor getCounselorByName(String name) {
        return counselorMapper.selectByName(name);
    }

    @Override
    public List<Counselor> getCounselorsByFacultyName(String facultyName) {
        return counselorMapper.selectByFacultyName(facultyName);
    }

    @Override
    public List<Counselor> getCounselorsByFacultyId(Integer facultyId) {
        return counselorMapper.selectByFacultyId(facultyId);
    }

    @Override
    public Counselor updateCounselor(Counselor counselor) {
        counselorMapper.updateCounselor(counselor);
        return counselor;
    }

    @Override
    public User createUser(User user) {
        userMapper.insertUser(user);
        Integer roleId = null;
        if ("office".equalsIgnoreCase(user.getType())) {
            roleId = 1;
        } else if ("faculty".equalsIgnoreCase(user.getType())) {
            roleId = 2;
        } else if ("counselor".equalsIgnoreCase(user.getType())) {
            roleId = 3;
        }
        if (roleId != null && user.getId() != null) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleMapper.insertUserRole(userRole);
        }
        return user;
    }
}
